package com.sam.thread.demo1;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * Created by SamZhao on 2017/5/29.
 */
public class Tickets implements Runnable {

    private int ticket = 100;

    /**
     * JDK 1.5之后 使用接口Lock 替换同步代码块，实现线程安全性
     * Lock接口方法：
     *      lock();获取锁
     *      unlock();释放锁
     *
     * 实现类ReentrantLock
     *
     *
     *
     */
    private Lock lock = new ReentrantLock();

    public void run() {
        while(true){
            method();

        }
    }

    private void method() {
        lock.lock();
        if(ticket > 0){
            try {
                Thread.sleep(10);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName()+" 正在出售第 " + ticket-- + " 张票...");
        }
        lock.unlock();
    }
}
